// A lot of stuff needs to be done inside the callbacks because
// there's usually a lag, which means lines after the chrome.bookmarks
// API call will be executed BEFORE the callback. For example, if you
// try to set a variable inside the callback and then use it to call a
// function OUTSIDE the callback, it will fail because the latter function
// call will run first. Weak sauce.
const bookmarkName = "chrome quotes data";
const bookmarkUrl = "http://chromequotes/?data=";

function readBookmark(callback) {
  chrome.bookmarks.search(bookmarkName, function(node) {
    if (node.length === 0) {
      writeBookmark(callback);
    } else {
      try {
        var data = JSON.parse(node[0].url.replace(bookmarkUrl, "")
          .replace(/\%22/g, '"')
          .replace(/\%3E/g, ">"));
        for (var key in data) {
          localStorage[key] = data[key];
        }
        callback();
      } catch(e) {
        alert(chrome.i18n.getMessage("syncError"));
        writeBookmark(callback);
      }
    }
  });
}

function writeBookmark(callback) {
  // Need to use a callback because putting the function inside the API
  // call screws with the scope
  chrome.bookmarks.getTree(function(tree) {
    chrome.bookmarks.search(bookmarkName, function(node) {
      if (node.length === 0) {
        chrome.bookmarks.create({
          parentId: tree[0].children[1].id,
          title: bookmarkName,
          url: bookmarkUrl + JSON.stringify(localStorage)
        }, function() { callback(); });
      } else {
        chrome.bookmarks.update(node[0].id, {
          url: bookmarkUrl + JSON.stringify(localStorage)
        }, callback);
      }
    });
  });
}

function sync(callback) {
  readBookmark(callback);
}

if (Settings.sync()) {
  chrome.bookmarks.onChanged.addListener(function(id, changeInfo) {
    alert("Bookmark changed! Now syncing!");
  });
}